package com.jokelandave.poc.server.dao;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyFactory;
import com.googlecode.objectify.ObjectifyService;
import com.jokelandave.poc.server.domain.Team;

public class TeamDao {
	
	public TeamDao()
	{

	}
	
	public Team getTeamByKey(Key<Team> teamKey)
	{
		Team toReturn;
		Objectify obj = ObjectifyService.beginTransaction();
		try
		{
			toReturn = obj.get(teamKey);
			obj.getTxn().commit();
		}
		finally
		{
			if(obj.getTxn().isActive())
			{
				obj.getTxn().rollback();
			}
		}
		return toReturn;
	}

	public Key<Team> putTeam(Team toPut) 
	{
		Key<Team> toReturn;
		Objectify obj = ObjectifyService.beginTransaction();
		try
		{
			toReturn = obj.put(toPut);
			obj.getTxn().commit();
		}
		finally
		{
			if(obj.getTxn().isActive())
			{
				obj.getTxn().rollback();
			}
		}
		return toReturn;
	}
	
	public Team putAndGet(Team team)
	{
		
		ObjectifyFactory fact = ObjectifyService.factory();
		
		fact.register(Team.class);
		
		Team toReturn = null;
		
		Objectify obj = fact.begin();
		
		try
		{
			Key<Team> teamKey = obj.put(team);
			toReturn = obj.find(teamKey);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return toReturn;
		
	}
	
//	public List<Team> getTeamsBySport(Sport sport)
//	{
//		return obj.query(Team.class).filter("sport =", sport).list();
//	}
//	
//	public List<Team> getTeamsByLocation(String location)
//	{
//		return obj.query(Team.class).filter("location =", location).list();
//	}
	
}
